<template>
  <div>
    <el-upload
      list-type="picture-card"
      action=""
      :on-preview="handlePictureCardPreview"
      :file-list="fileList"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :http-request="upload"
      :limit="limit"
      :class="{ hidden: fileList.length >= limit }"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" title="图片预览">
      <img width="100%" :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      dialogVisible: false,
      imgUrl: '',
      fileList: []
    }
  },
  created() {
    this.cos = new COS({
      SecretId: 'AKIDvdOzNe2P00qTvGS6IMKC1sc8NQTVuH5i', // 身份识别 ID
      SecretKey: 'DsIWgjrBNOYgMZbU7rgJBXnJgpmX5oTa' // 身份密钥
    })
  },
  methods: {
    upload({ file }) {
      // console.log('我需要自己上传', file)
      this.cos.putObject({
        Bucket: 'hr-83-1256173530', /* 必须 存储桶名字 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: Date.now() + '-' + parseInt(Math.random() * 1000) + '-' + file.name, /* 必须 上传的文件名 */
        StorageClass: 'STANDARD',
        Body: file // 上传文件对象
        // onProgress: function(progressData) {
        //   console.log(JSON.stringify(progressData))
        // }
      }, (err, data) => {
        if (err) return this.$message.error(err)
        // console.log('上传的结果', data)
        // 找到组件上传的图片和上传腾讯云成功后返回的图片 => 相同的t, 更换线上地址
        const res = this.fileList.find(item => item.uid === file.uid)
        res.status = 'success'
        res.url = 'http://' + data.Location
      })
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.imgUrl = file.url
      this.dialogVisible = true
    },
    // 移除图片 file: 删除的图片 fileList: 剩下的文件列表
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    // 添加图片
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    // 上传之前的校验
    beforeUpload(file) {
      // 判断上传的文件的格式
      const accepts = ['image/gif', 'image/png', 'image/jpeg']
      if (!accepts.includes(file.type)) {
        this.$message.warning('上传的图片格式错误')
        return false
      }
      if (file.size >= 1 * 1024 * 1024) {
        this.$message.warning('上传的文件不能超过1MB')
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.hidden {
  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
